package com.fieldchain.ex.fa100.ui.trade.string;

import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.fieldchain.ex.fa100.inter.StringCallBack;
import com.fieldchain.ex.fa100.inter.TradTextLsitener;

import com.fieldchain.ex.fa100.utils.string.DoubleParse;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/27
 */
public class TradTextWtcher {
    private TradTextLsitener listener;
    private double price,num;
    private boolean isWork=false;
    public TradTextWtcher(EditText etPrice, EditText etNum, final TradTextLsitener listener) {
        price=0;
        num=0;
        this.listener=listener;
        watch(etPrice, new StringCallBack() {
             @Override
             public void message(String msg) {
                 price= DoubleParse.parse(msg);
                 if(price>0) {
                     listener.priceAbout(price);
                     check(listener);
                 }
             }
         });
        watch(etNum, new StringCallBack() {
            @Override
            public void message(String msg) {
                num=DoubleParse.parse(msg);
                check(listener);
            }
        });
    }

    public void check(TradTextLsitener listener){
        if(num*price>0){
            listener.amount(num*price);
        }else{
            listener.amount(0.00);
        }
    }

    public void watch(EditText et, final StringCallBack callBack){
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(isWork)return;
                isWork=true;
                if(editable.length()==0){
                    callBack.message(0.00+"");
                }else{
                    callBack.message(editable.toString());
                }
                SystemClock.sleep(5);
                isWork=false;

            }
        });
    }
}
